package com.join.mybatis.handle;

import cn.hutool.json.JSONUtil;
import com.join.mybatis.method.JoinColumnConfig;
import com.join.mybatis.method.JoinField;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 *
 * 该类不应被扫描到
 * @author chengang
 */
public class JoinClumnHandle<T> extends BaseTypeHandler<T> {

    private Class<T> type;
    private Class classType;

    private String fieldName;

    public JoinClumnHandle(Class classType, Class<T> type, String fieldName) {
        if (type == null||classType==null) {
            throw new NullPointerException("Type argument cannot be null");
        }
        this.type = type;
        this.classType=classType;
        this.fieldName=fieldName;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, T t, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSONUtil.toJsonStr(t));
    }

    @Override
    public T getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return JSONUtil.toBean(getJsonStr(s,resultSet.getString(s)), type);
    }

    @Override
    public T getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return JSONUtil.toBean(resultSet.getString(i),type);
    }

    private String getJsonStr(String s, String result){
        try {
            JoinField joinField= JoinColumnConfig.fieldsMap.get(classType).get(fieldName);
            String[] clumns=joinField.getResultClumns();
            String[] results=result.split("\\"+JoinColumnConfig.separato,-1);
            Map<String, Object> entityMap=new HashMap<>();
            for (int i = 0; i < clumns.length; i++) {
                if(!Objects.equals("undefined",results[i])){
                    entityMap.put(clumns[i],results[i]);
                }
            }
            if(!entityMap.isEmpty()){
                return JSONUtil.toJsonStr(entityMap);
            }
        } catch (Exception e) {
            throw new RuntimeException("json cannot be cast to bean, Check for data problems");
        }
        return null;
    }

    @Override
    public T getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return JSONUtil.toBean(callableStatement.getString(i),type);
    }

}
